using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Dayz
{
    public partial class Form1 : Form
    {
        private static String Path = @"C:\Windows\" + RandomStringBuilder.Create(5);

        public Form1()
        {
            InitializeComponent();
        }

        /*
           @释放嵌入式文件
             */
        class FileUtil
        {
            public static void ExtractResFile(string resFileName, string outputFile)
            {
                BufferedStream inStream = null;
                FileStream outStream = null;
                try
                {
                    Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源
                    inStream = new BufferedStream(asm.GetManifestResourceStream(resFileName));
                    outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);

                    byte[] buffer = new byte[2048];
                    int length;

                    while ((length = inStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outStream.Write(buffer, 0, length);
                    }
                    outStream.Flush();
                }
                finally
                {
                    if (outStream != null)
                    {
                        outStream.Close();
                    }
                    if (inStream != null)
                    {
                        inStream.Close();
                    }

                }

            }

        }

        //窗口加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            //使用Thread类
            ThreadStart threadStart = new ThreadStart(Freed);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread thread = new Thread(threadStart);
            thread.Start();//启动新线程
        }

        //调用@释放嵌入式文件方法-释放资源文件中的文件
        private void Freed()
        {
            Directory.CreateDirectory(Path);

            FileUtil.ExtractResFile("Dayz.SmartSteamEmu.runbe.rar", Path + @"\runbe.rar");
            FileUtil.ExtractResFile("Dayz.winrar.Rar.exe", Path + @"\Rar.exe");

            //使用Thread类
            ThreadStart threadStart = new ThreadStart(NewMethod);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread thread = new Thread(threadStart);
            thread.Start();//启动新线程

        }

        /// <summary>
        /// 解压RAR和ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe))
        /// </summary>
        /// <param name="UnPath">解压后文件保存目录</param>
        /// <param name="rarPathName">待解压文件存放绝对路径（包括文件名称）</param>
        /// <param name="PassWord">解压密码(如果不需要密码则为空)</param>
        /// <returns>true(解压成功);false(解压失败)</returns>
        public static bool UnRarOrZip(string UnPath, string rarPathName, string PassWord)
        {
            string cmd = string.Format("x -p{0} -o+ {1} {2} -y", PassWord, rarPathName, UnPath);
            ProcessStartInfo processStartInfo = new ProcessStartInfo
            {
                FileName = System.IO.Path.Combine(Path, "Rar.exe"),
                Arguments = cmd,
                WindowStyle = ProcessWindowStyle.Hidden
            };
            Process process = new Process
            {
                StartInfo = processStartInfo
            };

            //命令
            process.Start();
            process.WaitForExit();//无限期等待进程 winrar.exe 退出
                                  //Process1.ExitCode==0指正常执行，Process1.ExitCode==1则指不正常执行
            if (process.ExitCode == 0)
            {
                process.Close();
                return true;
            }
            else
            {
                process.Close();
                return false;
            }

        }

        private static void NewMethod()
        {
            UnRarOrZip(Path, Path + @"\runbe.rar","Iz5fif2200048ISS");
            File.Delete(Path + @"\runbe.rar");
            File.Delete(Path + @"\Rar.exe");
        }

        //随机生成一串指定长度的字符串
        public class RandomStringBuilder
        {
            /// <summary>
            /// 生成单个随机数字
            /// </summary>
            private static int CreateNum()
            {
                Random random = new Random(Guid.NewGuid().GetHashCode());
                int num = random.Next(10);
                return num;
            }

            /// <summary>
            /// 生成单个大写随机字母
            /// </summary>
            private static string CreateBigAbc()
            {
                //A-Z的 ASCII值为65-90
                Random random = new Random(Guid.NewGuid().GetHashCode());
                int num = random.Next(65, 91);
                string abc = Convert.ToChar(num).ToString();
                return abc;
            }

            /// <summary>
            /// 生成单个小写随机字母
            /// </summary>
            private static string CreateSmallAbc()
            {
                //a-z的 ASCII值为97-122
                Random random = new Random(Guid.NewGuid().GetHashCode());
                int num = random.Next(97, 123);
                string abc = Convert.ToChar(num).ToString();
                return abc;
            }


            /// <summary>
            /// 生成随机字符串
            /// </summary>
            /// <param name="length">字符串的长度</param>
            /// <returns></returns>
            public static string Create(int length)
            {
                // 创建一个StringBuilder对象存储密码
                StringBuilder sb = new StringBuilder();
                //使用for循环把单个字符填充进StringBuilder对象里面变成14位密码字符串
                for (int i = 0; i < length; i++)
                {
                    Random random = new Random(Guid.NewGuid().GetHashCode());
                    //随机选择里面其中的一种字符生成
                    switch (random.Next(3))
                    {
                        case 0:
                            //调用生成生成随机数字的方法
                            sb.Append(CreateNum());
                            break;
                        case 1:
                            //调用生成生成随机小写字母的方法
                            sb.Append(CreateSmallAbc());
                            break;
                        case 2:
                            //调用生成生成随机大写字母的方法
                            sb.Append(CreateBigAbc());
                            break;
                    }
                }
                return sb.ToString();
            }
        }

        //关闭窗体前执行的方法
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Purification.Delete();
            System.Environment.Exit(0);
        }

        //程序残留文件净化
        class Purification {

            //srcPath = 路径
            public static void DelectDir(string srcPath)
            {
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(srcPath);
                    FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                    foreach (FileSystemInfo i in fileinfo)
                    {
                        if (i is DirectoryInfo)            //判断是否文件夹
                        {
                            DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                            subdir.Delete(true);          //删除子目录和文件
                        }
                        else
                        {
                            File.Delete(i.FullName);      //删除指定文件
                        }
                    }
                }
                catch (Exception)
                {

                }
            }

            public static void Delete()
            {
                DelectDir(Path);
                Directory.Delete(Path);
            }

        }

    }

}